﻿var heartBeat = new (function () {
    var inter = null;

    this.start = function () {
        this.stop();
        inter = setInterval(function () {
            ws.send(0, '', true);
        }, 5000);
    };

    this.stop = function () {
        if (inter) {
            clearInterval(inter);
            inter = null;
        }
    };
});

var ws = new (function () {
    var socket = null;
    var stopCountdown = null;

    var win = {
        qqWin: null
    };

    function pro_cmd(data) {
        var json = JSON.parse(data);

        var tid = json.tid;
        var content = json.content;

        if (tid > 0) {
            console.log('Receive\t:[' + tid + ']' + content);
        }

        switch (tid) {
            case 102:
                {
                    if (win.qqWin) {
                        win.qqWin.QQ.incUser(content);
                    }
                    break;
                }
            case 103:
                {
                    var wins = chrome.extension.getViews({ type: 'tab' });
                    if (wins.length == 1 && wins[0].location.href.indexOf('login.htm') > -1) {
                        wins[0].close();
                    }
                    var val = 'toolbar=0,scrollbars=0,location=no,statusbar=0,menubar=0,resizable=0,width=' + 290 + ',height=' + 650;
                    win.qqWin = window.open('123.htm#0', 'qqWin', val);

                    win.qqWin.addEventListener('load', function () {
                        this.QQ.loadUserList(content);
                    });

                    heartBeat.start();
                    break;
                }
            default:
        }
    }

    function onSocketClose() {
        console.log('onSocketClose!');
    }

    this.start = function () {
        if (!socket) {
            socket = new Socket('192.168.3.190', 5354, pro_cmd, onSocketClose);
        }
    };

    stop = function () {
        console.log('Shutting down!');

        heartBeat.stop();
        socket.Close();
        socket = null;

        console.log('Shut down!');
    };

    this.tryStop = function () {
        if (stopCountdown == null) {
            stopCountdown = setTimeout(stop, 1000);
        }
    }

    this.quitStop = function () {
        if (stopCountdown) {
            clearTimeout(stopCountdown);
            stopCountdown = null;
        }
    }

    this.send = function (tid, content, noLog) {
        switch (tid) {
            case 0: break;
            default:
                {
                    console.log('Send\t:[' + tid + ']' + content);
                    break;
                }
        }
        socket.Send(tid, content, noLog);
    }
});
